<?php

/**
 * Class Argumentation.php
 *
 * Class that deals with the storage/management of arguments inserted by users
 *
 * @author Jose Oliveira <jafo@ua.pt> 2012
 */

class Argumentation{

	private $argID;
	private $arg;
	Private $projectID;
	private $userID;
	private $dateHour;
	private $edited;
	private $argType;

	/**
	 * 
	 * @param string $arg
	 * @param integer $argType
	 * @param integer $projectID
	 * @param integer $userID
	 */
	function __construct($arg, $argType, $projectID, $userID){

		if(isset($arg) && isset($argType) && isset($projectID) && isset($userID)){
			$this->arg=$arg;
			$this->argType=$argType;
			$this->projectID=$projectID;
			$this->userID=$userID;
		}
	}

	/**
	 * Method that stores an argument on the table Argument case this is 
	 * not an edtition to a previously made question​​.
	 * return 0: storing of the question has failed
	 * return 1: improved question stored with success
	 * return 2: the question has been previously entered by the user
	 * @throws Exception
	 * @return integer
	 */
	
	public function addArg(){

		if($this->validArg($this->arg, $this->argType, $this->userID, $this->projectID)){
			$date=date("Y-m-d H:i:s");

			$conn=new ConnDBUser();
			$conn->connect();    //liga à base de dados com privilégios de utilizador web


			$arg=mysql_real_escape_string($this->arg);

			$result=mysql_query("insert into arg(arg, argType, edited, dateHour, userID, projectID, state)
			values('$arg', '" . $this->argType . "', '0' , '" . $date . "', '" . $this->userID . "', '" . $this->projectID . "', 1)");

			if(!$result){
				throw new Exception("Lamentamos mas ocorreu um erro" . mysql_error());
			}

			try{
				$conn->disconnect($result);
				return 1;

			}catch(Exception $e){
				$e->getMessage();
			}

		}else{
			return 2;
		}
	}

	/**
	 * Method that returns the info about all arguments of a user that haven't been edited
	 * @param integer $projectID
	 * @param integer $userID
	 * @throws Exception
	 * @return array
	 */
	public function getAllArgsOfUser($projectID, $userID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select argID from arg where edited='0' and projectID='$projectID' and userID='$userID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao carregar os argumentos inseridos");
		}

		try{
			$questArr=array();

			while($registo=mysql_fetch_array($result)){
				array_push($questArr, $registo['questionID']);
			}

			$conn->disconnect($result);
			return $questArr;

		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that returns the info about all arguments of a project that haven't been edited
	 * @param unknown_type $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getAllArgs($projectID){

		$conn = new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select argID from arg where projectID='$projectID' and edited='0'");  //query que obtem todas as questões que não foram editadas inerentes a um dado projeto

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao carregar os argumentos deste projeto");
		}

		try{
			$questArr=array();

			while($registo=mysql_fetch_array($result)){
				array_push($questArr, $registo['questionID']);
			}

			$conn->disconnect($result);
			return $questArr;
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that checks if an argument was edited
	 * @param integer $argID
	 * @throws Exception
	 * @return boolean
	 */
	public function isEdited($argID){
			
		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select edited from arg where argID='$argID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$registo=mysql_fetch_array($result);
			$conn->disconnect($result);

			if($registo['edited'] == 1){
				return true;
			}else{
				return false;
			}

		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that verifies if this argument has not yet been entered by this user 
	 * @param string $arg
	 * @param integer $argType
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return bool
	 */
	public function validArg($arg, $argType, $userID, $projectID){

		if($arg==""){
			return false;
		}

		$conn=new ConnDBUser();
		$conn->connect();

		$arg=mysql_real_escape_string($arg);
		$result=mysql_query("select * from arg where arg='$arg' and argType='$argType' and projectID='$projectID' and userID='$userID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);

			if($num==0){
				//significa que este utilizador está a inserir um argumento completamente novo
				return true;
			}else{
				return false;
			}
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that update de field "edited" of this argument to "1"
	 * @param integer $argID
	 * @throws Exception
	 * @return bool
	 */
	public function updateToEdited($argID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("update arg set edited='1' where argID='$argID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro: " . mysql_error());
		}

		try{
			$conn->disconnect($result);
			return true;
		}catch (Exception $e){
			$e->getMessage();
		}

		$conn->disconnect($result);
		return false;
	}

	/**
	 * Method that returns the IDs of all arguments that have been edited
	 * from a certain user. 
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function editedArgIDs($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select argID from arg where edited='1' and projectID='$projectID' and userID='$userID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num==0){
				$conn->disconnect($result);
				return 0;           //se não houverem questões editadas, não retornamos nada
			}else{
				$ids=array();

				while($registo=mysql_fetch_array($result)){
					$temp=$registo['argID'];       //criação de array uni-dimensional com os ID's das questões que sofreram edição
					array_push($ids, $temp);
				}

				$conn->disconnect($result);
				return $ids;
			}
		}catch(Exception $e){
			echo $e->getMessage();
		}

		$conn->disconnect($result);
		return 0;
	}

	/**
	 * Method that returns the info about all arguments of a user that haven't been edited
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getNoEditedArgInfo($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select argID, arg, argType, dateHour, projectID, userID from arg where userID='$userID' and projectID='$projectID' and edited='0' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ");
		}

		try{

			$num=mysql_num_rows($result);

			if($num>0){
				$info=array();
				while($registo=mysql_fetch_array($result)){
					array_push($info, $registo);
				}

					
				$conn->disconnect($result);
				return $info;
			}else{
				$conn->disconnect($result);
				return '';
			}



		}catch(Exception $e){
			echo $e->getMessage();
		}
	}

	/**
	 * Method used to unset a certain argument. Used when a user wants to delete a argument
	 * @param integer $argID
	 * @throws Exception
	 */
	public function unsetArg($argID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("update arg set state=0 where argID=$argID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$conn->disconnect($result);
			throw new Exception("Lamentamos mas ocorreu um erro ao eliminar o argumento");
		}catch(Exception $e){
			$e->getMessage();
		}
	}


	/**
	 * Returns the number of active arguments (not deleted by users) inserted by a certain user, 
	 * in a certain project, in the argumentation stage
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return integer
	 */
	public function getNumberOfArgs($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select argID from arg where projectID='$projectID' and userID='$userID' and state=1");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);
			return $num;

		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that returns an array with info properly formatted for the project administrator, with arguments, 
	 * edited and unedited from each user in a certain project
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 */
	public function preparedArrayForAdmin($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from arg where userID=$userID and projectID=$projectID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao obter as questões do grupo");
		}

		try{

			$firstArray=array();
			while($registo=mysql_fetch_array($result)){
				array_push($firstArray, $registo);
			}

			$conn->disconnect($result);

			//agora que já temos um array com todas as funções, vamos passá-lo por um método privado, que trata da verificação da existencia de edições
			$arrayFinal=$this->tuneAdminArray($firstArray);
			return $arrayFinal;

		}catch(Exception $e){
			$e->getMessage();
		}

			
	}

	/**
	 * Method that completes the array of the method preparedArrayForAdmin
	 * @param array $array
	 * @return array
	 */
	private function tuneAdminArray($array){

		$cleanArray=array();

		for($i=0; $i<count($array); $i++){

			if($array[$i]['edited']==1){

				//se for editado, vamos  buscar todas as versões:
				$edArg=new EditedArg('', '', '');
				$tempArray=$edArg->showPreviousVersionsOfArg($array[$i]['argID']);
				unset($edArg);
				$cleanArray=array_merge($cleanArray, $tempArray);
			}else{
				$tempArray=array("arg" => $array[$i]['arg'], "argType" => $array[$i]['argType'], "dateHour" => $array[$i]['dateHour'], "state" => $array[$i]['state'], "userID" => $array[$i]['userID'], "edited" => 0, "instance" => 0, "bold" => 1, "origArgID" => $array[$i]['argID']);
				array_push($cleanArray, $tempArray);
			}

		}

		return $cleanArray;
	}



}
?>